package com.atguigu.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.atguigu.springcloud.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class PaymentServiceImpl implements PaymentService {

    public String paymentInfo_OK(Integer id){
        //测试正常访问的方法 一定成功的方法
        return "线程池：" + Thread.currentThread().getName() + " paymentInfo_OK,id:"+id;
    }
/*
* 服务降级：出现问题或者超时时盗用兜底方法
* */
    @HystrixCommand(fallbackMethod = "paymentInfo_BadHandler",commandProperties = {
            //就是当方法调用时间超过了3秒时就掉用兜底方法paymentInfo_BadHandler 这里可以有多个降级的异常
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentInfo_Bad(Integer id){
        Date date = new Date();
        long timenew = date.getTime();
        int number = 5;
        try {
            //睡眠三秒  模拟超时
            TimeUnit.SECONDS.sleep(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + " paymentInfo_Bad,id:"+id + "耗时：  "+ (new Date().getTime() - timenew);
    }

    public String paymentInfo_BadHandler(Integer id){

        return "线程池：" + Thread.currentThread().getName() + " paymentInfo_BadHandler,id:"+id ;
    }


    /*
    * 服务熔断
    * */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期 经过多久后尝试一次恢复
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker( Integer id){

        if(id < 0){
            throw  new RuntimeException("***** id 不能为负数，id："+id);
        }
        String serialNumber = IdUtil.simpleUUID();

        return Thread.currentThread().getName()+"\t"+ "调用成功，流水号："+serialNumber;
    }

    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){

        return "fallback_***** id 不能为负数，id："+ id;
    }
}
